#include "headers/EmailSender.h"
#include <QDebug>
#include <QByteArray>

EmailSender::EmailSender(QObject *parent) : QObject(parent)
{
    m_socket = new QSslSocket(this);
    m_socket->setProtocol(QSsl::TlsV1_2);
    connect(m_socket, &QSslSocket::connected, this, &EmailSender::onConnected);
    connect(m_socket, &QSslSocket::readyRead, this, &EmailSender::onReadyRead);
    connect(m_socket, &QSslSocket::errorOccurred, this, &EmailSender::onErrorOccurred);
    connect(m_socket, &QSslSocket::sslErrors, this, &EmailSender::onSslErrors);
}

// 触发发送邮件
void EmailSender::sendVerificationCode(const QString &recipientEmail, const QString &code)
{
    m_recipient = recipientEmail;
    m_verificationCode = code;
    m_socket->connectToHostEncrypted(SMTP_SERVER, SMTP_PORT);
}

// 连接服务器成功后，开始SMTP协议交互
void EmailSender::onConnected()
{
    qDebug() << "✅ 已连接到QQ邮箱SMTP服务器";
    m_socket->write("HELO qq.com\r\n");
}

// 处理服务器响应
void EmailSender::onReadyRead()
{
    QByteArray response = m_socket->readAll();
    qDebug() << "📩 服务器响应:" << response;

    if (response.startsWith("220") || response.contains("250 HELO")) {
        m_socket->write("AUTH LOGIN\r\n");
    }
    else if (response.startsWith("334 VXNlcm5hbWU6")) {
        QByteArray encodedEmail = SENDER_EMAIL.toUtf8().toBase64();
        qDebug() << "发送编码后的邮箱:" << encodedEmail;
        m_socket->write(encodedEmail + "\r\n");
    }
    else if (response.startsWith("334 UGFzc3dvcmQ6")) {
        QByteArray encodedAuthCode = SENDER_AUTH_CODE.toUtf8().toBase64();
        qDebug() << "发送编码后的授权码:" << encodedAuthCode;
        m_socket->write(encodedAuthCode + "\r\n");
    }
    else if (response.startsWith("235")) {
        qDebug() << "✅ 授权成功";
        m_socket->write("MAIL FROM: <" + SENDER_EMAIL.toUtf8() + ">\r\n");
    }
    else if (response.contains("250 MAIL FROM")) {
        m_socket->write("RCPT TO: <" + m_recipient.toUtf8() + ">\r\n");
    }
    else if (response.contains("250 RCPT TO")) {
        m_socket->write("DATA\r\n");
    }
    else if (response.startsWith("354")) {
        QString emailContent =
            "From: <" + SENDER_EMAIL + ">\r\n"
                                       "To: <" + m_recipient + ">\r\n"
                            "Subject: 你的验证码\r\n\r\n"
                            "你的验证码是：" + m_verificationCode + "，5分钟内有效。\r\n"
                                   "请勿向他人泄露验证码。\r\n"
                                   ".\r\n";
        qDebug() << "发送邮件内容:" << emailContent;
        m_socket->write(emailContent.toUtf8());
    }
    else if (response.contains("250 OK")) {
        m_socket->write("QUIT\r\n");
        emit sendSuccess();
    }
    else if (response.startsWith("5")) {
        emit sendFailed("发送失败：" + response.trimmed());
        m_socket->disconnectFromHost();
    }
}

// 网络错误处理
void EmailSender::onErrorOccurred(QAbstractSocket::SocketError error)
{
    QString errorMsg = QString("网络错误（%1）：%2")
                           .arg(error).arg(m_socket->errorString());
    qDebug() << "❌" << errorMsg;
    emit sendFailed(errorMsg);
    m_socket->disconnectFromHost();
}

// SSL证书错误处理
void EmailSender::onSslErrors(const QList<QSslError> &errors)
{
    QStringList errorList;
    for (const auto &err : errors) {
        errorList << err.errorString();
    }
    qDebug() << "⚠️ SSL警告：" << errorList.join("; ");
    m_socket->ignoreSslErrors();
}
